﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
using System.IO;
using System.Text;

public class AssetsBundleBuilder
{
    [MenuItem("Custom/AssetBundle/BuildCompressAssets")]
    public static void BuildAndCompressAssets()
    {
        BuildAssets();
        CompressAssets();
        CopyCompressAssets();
    }

    private static void BuildAssets()
    {
        string destinationPath = PathDefine.BuildBundlePath;
        if (Directory.Exists(destinationPath)) {
            Directory.Delete(destinationPath, true);
        }
        Directory.CreateDirectory(destinationPath);

#if UNITY_ANDROID
        BuildTarget buildTarget = BuildTarget.Android;
#elif UNITY_IOS
        BuildTarget buildTarget = BuildTarget.iOS;
#else
        BuildTarget buildTarget = BuildTarget.StandaloneWindows;
#endif
        BuildPipeline.BuildAssetBundles(destinationPath
            , BuildAssetBundleOptions.DeterministicAssetBundle | BuildAssetBundleOptions.ChunkBasedCompression
            , buildTarget);
        writeFileList(PathDefine.BuildBundlePath);
    }

    private static void CompressAssets()
    {
        Debug.LogWarning("Compress Assets is not implementation");
    }

    private static void CopyCompressAssets()
    {
        string destPath = PathDefine.StreamingAssetsPath;
        destPath = destPath.Replace("file:///", "");
        if (Directory.Exists(destPath)) { Directory.Delete(destPath, true); }
        Directory.CreateDirectory(destPath);

        string inRoot = PathDefine.BuildAssetPath + "/";
        string[] allFiles = Directory.GetFiles(inRoot, "*.*", SearchOption.AllDirectories);
        for(int i=0; i<allFiles.Length; i++) {
            string name = allFiles[i];
            name = name.Replace(inRoot, "").Replace("\\", "/");

            string destName = destPath + "/" + name;
            string parentPath = Directory.GetParent(destName).FullName;
            if (!Directory.Exists(parentPath)) { Directory.CreateDirectory(parentPath); }

            File.Copy(inRoot + name, destName);
        }

    }

    private static void writeFileList(string inRoot)
    {
        StringBuilder sb = new StringBuilder();
        inRoot += "/";
        string[] names = Directory.GetFiles(inRoot, "*.*", SearchOption.AllDirectories);
        for(int i=0; i<names.Length; i++) {
            string name = names[i];
            name = name.Replace(inRoot, "").Replace("\\", "/");
            sb.Append(name);
            sb.Append("\n");
        }

        string listPath = PathDefine.BuildAssetPath + PathDefine.FileList;
        if (File.Exists(listPath)) { File.Delete(listPath); }
        StreamWriter fileList = File.CreateText(listPath);
        fileList.Write(sb.ToString());
        fileList.Close();
    }







}
